package DesignPattern.DynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理模式
 */
public class JDKProxy {
    /**
     * 维护一个目标对象
     */
    private Object target;

    public JDKProxy(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //代理实现额外的功能
                System.out.println("打印日志开始");
                //调用业务代码
                Object invoke = method.invoke(target, args);
                //代理实现的额外的功能
                System.out.println("打印日志结束");
                return invoke;
            }
        });
    }
}

class Test {
    public static void main(String[] args) {
        IShoppingService proxyInstance = (IShoppingService) new JDKProxy(new ShoppingService()).getProxyInstance();
        proxyInstance.shopping("车");
        /** 结果
         * 打印日志开始
         * 买车
         * 打印日志结束
         */
    }
}
